package vashion.azeroth.core.service.impl;

import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vashion.azeroth.core.manager.personal.PersonalMemberTokenManager;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalMemberToken;
import vashion.azeroth.core.service.PersonalMemberTokenService;

@Service
public class PersonalMemberTokenServiceImpl implements PersonalMemberTokenService<PersonalMemberToken> {
	
	@Autowired
	private PersonalMemberTokenManager personalMemberTokenManager;

	@Override
	public PersonalMemberToken createOrUpdateToken(PersonalMember member) {
		PersonalMemberToken token = personalMemberTokenManager.get(member.getMemberId());
		if(null != token) {
			token.setAccessToken(UUID.randomUUID().toString());
			token.setAccessTokenTimeOut(DateUtils.addSeconds(new Date(), 30*24*3600));
			token.setTimeEdit(new Date());
			
			personalMemberTokenManager.update(token);
		} else {
			token = new PersonalMemberToken();
			token.setMemberId(member.getMemberId());
			token.setMemberName(member.getMemberName());
			token.setAccessToken(UUID.randomUUID().toString());
			token.setAccessTokenTimeOut(DateUtils.addSeconds(new Date(), 30*24*3600));
			personalMemberTokenManager.save(token);
		}
		
		return token;
	}

	@Override
	public PersonalMemberToken getMemberToken(Long memberId) {
		PersonalMemberToken token = personalMemberTokenManager.get(memberId);
		return token;
	}

}
